import java.util.Stack;

public class Test05 {
    public static ListNode reverse1(ListNode root){
        ListNode pre = null;
        while(root != null){
            ListNode next= root.next;
            root.next = pre;
            pre = root;
            root = next;
        }
        return pre;
    }
    public static void reverse(ListNode root){
        Stack<ListNode> stack = new Stack<>();
        while(root !=null){
            stack.add(root);
            root = root.next;
        }
        ListNode temp;
        while(!stack.isEmpty()) {
            temp = stack.pop();
            System.out.println(temp.val);
        }
    }

    public static void main(String[] args) {
        ListNode root = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(4);
        ListNode node4 = new ListNode(5);
        root.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = null;
        reverse(root);
        ListNode listNode = reverse1(root);
        ListNode temp = listNode;
        while(temp !=null){
            System.out.println(temp.val);
            temp = temp.next;
        }

    }
}
class ListNode{
    int val;
    ListNode next;

    public ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
